package main

import (
	"fmt"
	"os"
	"time"

	"gitee.com/xingnan/toolbox/battery"
)

func printBattery(idx int, bat *battery.Battery) {
	fmt.Printf(
		"BAT%d: %s, %.2f%%",
		idx,
		bat.State,
		bat.Current/bat.Full*100,
	)
	defer fmt.Printf(" [Voltage: %.2fV (design: %.2fV)]\n", bat.Voltage, bat.DesignVoltage)

	var str string
	var timeNum float64
	switch bat.State {
	case battery.Discharging:
		if bat.ChargeRate == 0 {
			fmt.Print(", discharging at zero rate - will never fully discharge")
			return
		}
		str = "remaining"
		timeNum = bat.Current / bat.ChargeRate
	case battery.Charging:
		if bat.ChargeRate == 0 {
			fmt.Print(", charging at zero rate - will never fully charge")
			return
		}
		str = "until charged"
		timeNum = (bat.Full - bat.Current) / bat.ChargeRate
	default:
		return
	}
	duration, _ := time.ParseDuration(fmt.Sprintf("%fh", timeNum))
	fmt.Printf(", %s %s", duration, str)
}

func main() {
	batteries, err := battery.GetAll()
	if err, isFatal := err.(battery.ErrFatal); isFatal {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if len(batteries) == 0 {
		fmt.Fprintln(os.Stderr, "No batteries")
		os.Exit(1)
	}
	errs, partialErrs := err.(battery.Errors)
	for i, bat := range batteries {
		if partialErrs && errs[i] != nil {
			fmt.Fprintf(os.Stderr, "Error getting info for BAT%d: %s\n", i, errs[i])
			continue
		}
		printBattery(i, bat)
	}
}
